package test.wechat.rest;

import io.swagger.annotations.Api;
import lodsve.core.bean.ClientType;
import lodsve.web.mvc.properties.ServerProperties;
import lodsve.web.utils.RequestUtils;
import lodsve.wechat.api.oauth.WeChatOAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import springfox.documentation.annotations.ApiIgnore;

/**
 * .
 *
 * @author sunhao(sunhao.java @ gmail.com)
 * @version V1.0, 16/3/7 下午3:39
 */
@Api(value = "OAuth接口", description = "OAuth接口")
@Controller
@RequestMapping("/weixin")
public class OAuthController {
    @Autowired
    private WeChatOAuthService weChatOAuthService;
    @Autowired
    private ServerProperties serverProperties;

    /**
     * 跳转
     *
     * @param url 前台url
     * @return
     */
    @ApiIgnore
    @RequestMapping("/init")
    public String init(String url, String scope) {
        if (RequestUtils.getClientType() == ClientType.WEIXIN) {
            String redirect = weChatOAuthService.getOAuthUrl(serverProperties.getServerUrl() + "/weixin/openId", url, scope);
            return "redirect:" + redirect;
        }

        return "redirect:" + url;
    }

    /**
     * 获取openId
     *
     * @param url
     * @param code
     * @return
     */
    @ApiIgnore
    @RequestMapping("/openId")
    public String openId(String url, String code) {
        return "redirect:" + url + "?openId=" + weChatOAuthService.getOAuthToken(code).getOpenId();
    }
}
